package com.nhjf.mobile.controller.admin.courses;


import net.sf.json.JSONObject;
import com.nhjf.command.coursesSeries.CoursesSeriesCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.mobile.common.util.PictureUtil;
import com.nhjf.mobile.common.util.ProductPicUtil;
import com.nhjf.mobile.common.util.SysProperties;
import com.nhjf.model.coursesSeries.CoursesSeries;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.Organization;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.Courses;
import com.nhjf.model.teachers.CoursesType;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.coursesSeries.CoursesSeriesQo;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.OrganizationQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.pojo.qo.teachers.CoursesQo;
import com.nhjf.pojo.qo.teachers.CoursesTypeQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.coursesSeries.CoursesSeriesService;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.OrganizationService;
import com.nhjf.service.system.UserService;
import com.nhjf.service.teachers.CoursesService;
import com.nhjf.service.teachers.CoursesTypeService;
import com.nhjf.service.teachers.OperationLogService;
import com.nhjf.service.teachers.TeachersService;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/coursesAdmin")
public class CoursesAdminController  {
	@Autowired
	private CoursesService CoursesService;
	@Autowired
	private TeachersService teachersService;

	@Autowired
	private CoursesTypeService coursesTypeService;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private CoursesSeriesService coursesSeriesService;
	@Autowired
	private UserService userService;
	@Autowired
	private AdminSessionService adminSessionService;
	@Autowired
	private OrganizationService organizationService;
	private static String offFileName="offFlie";

	@ResponseBody
	@RequestMapping("/coursesType_Subctype")
	public String showSubctype(HttpServletRequest request, HttpServletResponse response, Model model,String typeOne,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==1 && user.getIsRole()==3) {
						CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
						coursesTypeQo.setpId(Long.parseLong(typeOne));
						coursesTypeQo.setType(2);
						List<CoursesType> list=coursesTypeService.queryList(coursesTypeQo);
						if(list!=null) {
							resMap.put("code", "200");
							resMap.put("message", list);
							return JSONObject.fromObject(resMap).toString();
						}else {
							resMap.put("code", "500");
							resMap.put("message", "系统异常!");
							return JSONObject.fromObject(resMap).toString();
						}
					}else {
						resMap.put("code", "500");
						resMap.put("message", "只能是老师和机构管理员才能登陆!");
						return JSONObject.fromObject(resMap).toString();
					}

				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}
			resMap.put("code", "500");
			resMap.put("message", "操作异常!");
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常!");
			return JSONObject.fromObject(resMap).toString();
		}
	}
	//课程列表
	@ResponseBody
	@RequestMapping(value = "/coursespage")
	public String coursescpage(HttpServletRequest request,@RequestParam(value="typeOne", required=false)Integer typeOne,@RequestParam(value="isReview", required=false)Integer isReview,@RequestParam(value="courseStatus", required=false)Integer courseStatus, Model model, @RequestParam(value = "page", defaultValue = "1") Integer page,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession!=null) {
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user!=null) {
				user.setUserPassword("");
				CoursesQo coursesQo = new CoursesQo();
				if(typeOne!=null) {
					coursesQo.setTypeOne(typeOne);
				}
				if(isReview!=null) {
					coursesQo.setIsReview(isReview);
				}
				if(courseStatus!=null) {
					coursesQo.setCourseSheries(courseStatus);
				}
				if(user.getIsRole()==1) {
					coursesQo.setSeachCoursesSeries(true);
					coursesQo.setSeachUploader(true);
					coursesQo.setNotaAeries(2);
					Pagination pagination = new Pagination();
					pagination.setPageSize(16);
					TeachersQo teachersQo=new  TeachersQo();
					teachersQo.setUserId(user.getId());
					Teacher teacher= teachersService.queryUnique(teachersQo);
					coursesQo.setUploaderId(teacher.getId());
					pagination.setCondition(coursesQo);
					pagination.setPageNo(page);
					pagination = CoursesService.queryPagination(pagination);
					List<Courses> list=(List<Courses>) pagination.getList();
					SysProperties sysProperties=SysProperties.getInstance();
					String imagePath=sysProperties.get("imagePath");
					for (Courses courses : list) {
						if(courses.getCoursesSeries().getCover()!=null) {
							if(courses.getCoursesSeries().getCover().indexOf(imagePath+"/img/")>=0) {
							}else {
								courses.getCoursesSeries().setCover(imagePath+"/img/"+courses.getCoursesSeries().getCover());
							}
						}
					}
					pagination.setList(list);
					resMap.put("CoursesQo", coursesQo);
					resMap.put("code", "200");
					resMap.put("message", pagination);
					return JSONObject.fromObject(resMap).toString();
				}else if(user.getIsRole()==3) {
					coursesQo.setSeachCoursesSeries(true);
					coursesQo.setSeachUploader(true);
					coursesQo.setNotaAeries(2);
					Pagination pagination = new Pagination();
					pagination.setPageSize(16);
					TeachersQo teachersQo=new  TeachersQo();
					teachersQo.setUserId(user.getId());
					teachersQo.setSeachOrganization(true);
					Teacher teacher= teachersService.queryUnique(teachersQo);
					coursesQo.setOrganizationId(teacher.getTraininginstitution().getId());
					pagination.setCondition(coursesQo);
					pagination.setPageNo(page);
					pagination = CoursesService.queryPagination(pagination);
					List<Courses> list=(List<Courses>) pagination.getList();
					SysProperties sysProperties=SysProperties.getInstance();
					String imagePath=sysProperties.get("imagePath");
					for (Courses courses : list) {
						if(courses.getCoursesSeries().getCover()!=null) {
							if(courses.getCoursesSeries().getCover().indexOf(imagePath+"/img/")>=0) {
							}else {
								courses.getCoursesSeries().setCover(imagePath+"/img/"+courses.getCoursesSeries().getCover());
							}
						}
					}
					pagination.setList(list);
					resMap.put("CoursesQo", coursesQo);
					resMap.put("code", "200");
					resMap.put("message", pagination);
					return JSONObject.fromObject(resMap).toString();
				}else {
					resMap.put("code", "500");
					resMap.put("message", "只能老师和机构管理员才能登陆");
					return JSONObject.fromObject(resMap).toString();
				}
			}else {
				resMap.put("code", "406");
				resMap.put("message", "请先登录!");
				return net.sf.json.JSONObject.fromObject(resMap).toString();
			}
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return JSONObject.fromObject(resMap).toString();

	}



	//视频上传
	@ResponseBody
	@RequestMapping(value = "/uploadFile")
	public String uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse response,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		String fileVideoName="";

		AdminSessionQo adminSessionQo=new AdminSessionQo();
		adminSessionQo.setToken(token);
		AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
		if(adminSession!=null) {
			UserQo userQo=new UserQo();
			userQo.setUserName(adminSession.getLoginName());
			User user= userService.queryUnique(userQo);
			if(user!=null) {
				user.setUserPassword("");
				if(user.getIsRole()==4) {
					resMap.put("code", "500");
					resMap.put("message", "最高管理员不能操作!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}else {
					try {
						//判断文件是否为空
						if (file.isEmpty()) {
							resMap.put("code", "500");
							resMap.put("message", "上传文件不可为空");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}

						String fileName = offFileName;
						fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ fileName;
						fileVideoName=fileName+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
						String extension = FilenameUtils.getExtension(fileVideoName);
						String[] regular = { "MP4"};
						boolean flag = false;
						// 判断视频格式是否合规
						for (String str : regular) {
							if (extension.equalsIgnoreCase(str)) {
								flag = true;
							}
						}
						if (!flag) {
							try {
								throw new Exception("只能上传MP4格式！上传失败！");
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						//加个时间戳，尽量避免文件名称重复
						SysProperties sysProperties=SysProperties.getInstance();
						String filePath=sysProperties.get("temporaryFileUploadPath");
						String path = filePath +user.getId()+"/"+fileName+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
						//String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
						//创建文件路径.
						File dest = new File(path);
						ProductPicUtil productPicUtil = new ProductPicUtil();
						//判断文件是否已经存在
						if (dest.exists()) {
							dest.delete();
						}
						//判断文件父目录是否存在
						if (!dest.getParentFile().exists()) {
							dest.getParentFile().mkdir();
						}
						//上传文件
						file.transferTo(dest);
						//保存文件
						//            ServiceResultDto bc=CoursesService.findadd(new CoursesQo());
					} catch (IOException e) {
						e.printStackTrace();

					}
					resMap.put("code", "200");
					resMap.put("message", fileVideoName);
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}

			}else {
				resMap.put("code", "406");
				resMap.put("message", "请先登录!");
				return net.sf.json.JSONObject.fromObject(resMap).toString();
			}
		}
		resMap.put("code", "500");
		resMap.put("message", "系统繁忙");
		return net.sf.json.JSONObject.fromObject(resMap).toString();

	}





	//id课程查看
	@RequestMapping("/View_to")
	@ResponseBody
	public String view(HttpServletRequest request,HttpServletResponse response,String id ,Model model,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员不能操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
					Courses courses= CoursesService.get(Long.parseLong(id));
					if(null!=courses ) {
						SysProperties sysProperties=SysProperties.getInstance();
						String imagePath=sysProperties.get("imagePath");
						resMap.put("imagePath",imagePath);
						resMap.put("code", "200");
						resMap.put("message", courses);
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
				}
				resMap.put("code", "406");
				resMap.put("message", "请先登录!");
				return net.sf.json.JSONObject.fromObject(resMap).toString();
			}
			resMap.put("code", "406");
			resMap.put("message", "操作异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		}
	}


	//系列课视频添加
	@ResponseBody
	@RequestMapping(value= "/course_add")
	public String save(String fileName,HttpServletRequest request,HttpServletResponse response,CoursesQo qo,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员不能操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					} else if(user.getIsRole()==1 || user.getIsRole()==3) {
						if(StringUtils.isEmpty(fileName)) {
							resMap.put("code", "500");
							resMap.put("message", "请上传视频!");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}
						if(qo.getSeriesId()==null) {
							resMap.put("code", "500");
							resMap.put("message", "必须选择系列课!");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}
						CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
						coursesSeriesQo.setCoursesSeriesId(qo.getSeriesId());
						coursesSeriesQo.setSeachTeacher(true);
						CoursesSeries coursesSeries=coursesSeriesService.queryUnique(coursesSeriesQo);
						if(coursesSeries.getIsRelease()==2) {
							resMap.put("code", "500");
							resMap.put("message", "课程已发布!");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}
						/*				if (pic.isEmpty()) {
							resMap.put("code", "500");
							resMap.put("message", "上传图片不可为空");
							return JSONObject.fromObject(resMap).toString();
						}
						 */				int returnTag = -1;
						 SysProperties sysProperties=SysProperties.getInstance();
						 String fileTemPath=sysProperties.get("temporaryFileUploadPath");
						 String filePath=sysProperties.get("fileUploadPath");
						 //				String imgPath=sysProperties.get("imagePath");
						 //				//获取图片原始文件名
						 //				String originalFilename = pic.getOriginalFilename();
						 //				System.out.println(originalFilename);
						 //文件名使用当前时间
						 String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
						 // 获取上传图片的扩展名(jpg/png/...)
						 //				String extension = FilenameUtils.getExtension(originalFilename);
						 //				String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
						 //				boolean flag = false;
						 //				// 判断文件格式是否合法
						 //				for (String str : regular) {
						 //					if (extension.equalsIgnoreCase(str)) {
						 //						flag = true;
						 //					}
						 //				}
						 //				if (!flag) {
						 //					returnTag = 0;
						 //					resMap.put("code", "500");
						 //					resMap.put("message", "上传图片格式不正确！");
						 //					return JSONObject.fromObject(resMap).toString();
						 //				}
						 // 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
						 //				String path =imgPath + name + "." + extension;
						 //图片上传的绝对路径

						 //				File dir = new File(path);
						 //				if (!dir.exists()) {
						 //					dir.mkdirs();
						 //				}
						 //				// 上传图片
						 //				pic.transferTo(new File(path));
						 //保存课程信息
						 TeachersQo teachersQo=new TeachersQo();
						 teachersQo.setSeachOrganization(true);
						 teachersQo.setUserId(user.getId());
						 Teacher teacher=teachersService.queryUnique(teachersQo);
						 PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+"organization"+teacher.getTraininginstitution().getId()+"/"+fileName);
						 File source = new File(filePath+"organization"+teacher.getTraininginstitution().getId()+"/"+fileName);
						 if(coursesSeries.getCourseShare()==1) {
							 OrganizationQo organizationQo=new OrganizationQo();
							 organizationQo.setOrganizationid(teacher.getTraininginstitution().getId());
							 Organization organization= organizationService.queryUnique(organizationQo);
							 if(organization.getStorageSize()==null) {
								 organization.setStorageSize(source.length()/(1024*1024));
							 }
							 organization.setStorageSize(organization.getStorageSize()+source.length()/(1024*1024));
							 organizationService.update(organization);
						 }
						 Encoder encoder = new Encoder();
						 String length = "";
						 MultimediaInfo m = encoder.getInfo(source);
						 System.out.println("-------"+m.getDuration());
						 long ls = m.getDuration()/1000;
						 int hour = (int) (ls/3600);
						 int minute = (int) (ls/60);
						 int second = (int) (ls-minute*60);
						 length = minute+":"+second;
						 if(coursesSeries!=null) {
							 if(coursesSeries.getTotalLength()!=null) {
								 String[] fen= coursesSeries.getTotalLength().split(":");
								 String lengths="";
								 Integer i=Integer.parseInt(fen[0]); 
								 Integer j=Integer.parseInt(fen[1]); 
								 int fens= i+minute;
								 int miaos= j+second;
								 if(miaos>60) {
									 fens++;
									 miaos= miaos-60;
								 }
								 lengths=fens+":"+miaos+"";
								 coursesSeries.setTotalLength(lengths);
								 coursesSeriesService.update(coursesSeries);
							 }else {
								 coursesSeries.setTotalLength(length);
								 coursesSeriesService.update(coursesSeries);
							 }
						 }
						 System.out.println(length);
						 if(teacher==null) {
							 resMap.put("code", "500");
							 resMap.put("message", "没有找到老师!");
							 return net.sf.json.JSONObject.fromObject(resMap).toString();
						 }
						 qo.setUploaderId(teacher.getId());
						 qo.setVideo("organization"+teacher.getTraininginstitution().getId()+"/"+fileName);
						 //				qo.setImge(name + "." + extension);
						 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						 java.util.Date  date=new java.util.Date();
						 qo.setReleasetime(date);
						 qo.setViewTime(length);
						 qo.setIsReview(0);
						 ServiceResultDto serviceResultDto=CoursesService.findadd(qo);
						 if(serviceResultDto.getSuccess()) {
							 OperationLog operationLog=new OperationLog();
							 operationLog.setOperationType(2);
							 operationLog.setOperationDescription("课程添加!");
							 operationLog.setUserId(user);
							 operationLog.setOperationTime(new Date());
							 operationLog.setOperationUserName(user.getUserName());
							 operationLogService.save(operationLog);
							 resMap.put("code", "200");
							 resMap.put("message", "课程添加成功!");
							 return net.sf.json.JSONObject.fromObject(resMap).toString();
						 }
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}else {
				resMap.put("code", "406");
				resMap.put("message", "请先登录!");
				return net.sf.json.JSONObject.fromObject(resMap).toString();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return net.sf.json.JSONObject.fromObject(resMap).toString();
	}


	//课程修改course_update
	@ResponseBody
	@RequestMapping(value= "/course_update")
	public String update(HttpServletRequest request, HttpServletResponse response, Model model,String fileName,CoursesQo q,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==3 && user.getIsRole()==1) {
						SysProperties sysProperties1=SysProperties.getInstance();
						String fileTemPath=sysProperties1.get("temporaryFileUploadPath");
						String filePath=sysProperties1.get("fileUploadPath");
						//			SysProperties sysProperties=SysProperties.getInstance();
						//			String imgPath=sysProperties.get("imagePath");
						if ( user== null) {
							// 跳转到登录页面
							response.sendRedirect(request.getContextPath()+"/login");
						}
						if(q.getCoursesId()==null) {
							resMap.put("code", "404");
							resMap.put("message", "没有此账号！");
							return JSONObject.fromObject(resMap).toString();
						}
						CoursesQo coursesQo=new CoursesQo();
						coursesQo.setCoursesId(q.getCoursesId());
						Courses courses=CoursesService.queryUnique(coursesQo);
						//			MultipartFile pic = null;
						boolean isMultipart = ServletFileUpload.isMultipartContent(request);
						if (isMultipart){ 
							MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
							TeachersQo teachersQo=new TeachersQo();
							teachersQo.setUserId(user.getId());
							Teacher teacher=teachersService.queryUnique(teachersQo);
							//				pic = multipartRequest.getFile("pic");
							//				if(pic==null) {
							if(StringUtils.isNotBlank(fileName)) {
								resMap.put("code", "500");
								resMap.put("message", "请上传视频!");
								return net.sf.json.JSONObject.fromObject(resMap).toString();
							}
							ServiceResultDto ts= CoursesService.findpmodify(q);
							if(ts.getSuccess()) {
								OperationLog operationLog=new OperationLog();
								operationLog.setOperationType(3);
								operationLog.setOperationDescription("课程修改!");
								operationLog.setUserId(user);
								operationLog.setOperationTime(new Date());
								operationLog.setOperationUserName(user.getUserName());
								operationLogService.save(operationLog);
								resMap.put("code", "200");
								resMap.put("message", "课程修改成功!");
								return net.sf.json.JSONObject.fromObject(resMap).toString();
							}
						}else {


							//					String imge =imgPath+courses.getCoursesSeries().getCover();
							//					File dest = new File(imge);
							//					// 路径为文件且不为空则进行删除  
							//					if (dest.isFile() && dest.exists()) {  
							//						dest.delete();  
							//					}
							//					if (pic.isEmpty()) {
							//						resMap.put("code", "500");
							//						resMap.put("message", "上传图片不可为空");
							//						return JSONObject.fromObject(resMap).toString();
							//					}
							int returnTag = -1;

							// 获取图片原始文件名
							//					String originalFilename = pic.getOriginalFilename();
							//					System.out.println(originalFilename);
							//文件名使用当前时间
							String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
							// 获取上传图片的扩展名(jpg/png/...)
							//					String extension = FilenameUtils.getExtension(originalFilename);
							//					String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
							//					boolean flag1 = false;
							//					// 判断文件格式是否合法
							//					for (String str : regular) {
							//						if (extension.equalsIgnoreCase(str)) {
							//							flag1 = true;
							//						}
							//					}
							//					if (!flag1) {
							//						returnTag = 0;
							//						resMap.put("code", "500");
							//						resMap.put("message", "上传图片格式不正确！");
							//						return JSONObject.fromObject(resMap).toString();
							//					}
							// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
							//					String path =imgPath + name + "." + extension;
							//					//图片上传的绝对路径
							//					File dir = new File(path);
							//					if (!dir.exists()) {
							//						dir.mkdirs();
							//					}
							//					// 上传图片
							//					pic.transferTo(new File(path));
							if(StringUtils.isNotBlank(fileName)) {
								resMap.put("code", "500");
								resMap.put("message", "请上传视频!");
								return net.sf.json.JSONObject.fromObject(resMap).toString();
							}
							//					PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
							//					File source = new File(filePath+user.getId()+"/"+fileName);
							//					Encoder encoder = new Encoder();
							//					String length = "";
							//					MultimediaInfo m = encoder.getInfo(source);
							//					System.out.println("-------"+m.getDuration());
							//					long ls = m.getDuration()/1000;
							//					int hour = (int) (ls/3600);
							//					int minute = (int) (ls/60);
							//					int second = (int) (ls-hour*3600-minute*60);
							//					length = minute+":"+second;
							//					q.setViewTime(length);
							//					q.setImge(name + "." + extension);
							ServiceResultDto ts= CoursesService.findpmodify(q);
							if(ts.getSuccess()) {
								OperationLog operationLog=new OperationLog();
								operationLog.setOperationType(3);
								operationLog.setOperationDescription("课程修改!");
								operationLog.setUserId(user);
								operationLog.setOperationTime(new Date());
								operationLog.setOperationUserName(user.getUserName());
								operationLogService.save(operationLog);
								resMap.put("code", "200");
								resMap.put("message", "课程修改成功!");
								return net.sf.json.JSONObject.fromObject(resMap).toString();
							}
						}
						//			}else {
						if(StringUtils.isNotBlank(fileName)) {
							resMap.put("code", "500");
							resMap.put("message", "请上传视频!");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}
						ServiceResultDto ts= CoursesService.findpmodify(q);
					}else{
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}


			//			}

		} catch (Exception e) {
			// TODO: handle exception
			resMap.put("code", "500");
			resMap.put("message", "系统异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return net.sf.json.JSONObject.fromObject(resMap).toString();
	}


	//课程删除
	@ResponseBody
	@RequestMapping("/course_delete")
	public String delete(HttpServletRequest request,HttpSession session,HttpServletResponse response,String id,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
					if(id==null && id=="") {
						resMap.put("code", "500");
						resMap.put("message", "没有找到该课程!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}else{
						CoursesQo coursesQo=new CoursesQo();
						coursesQo.setCoursesId(Long.parseLong(id));
						coursesQo.setSeachUploader(true);
						coursesQo.setSeachCoursesSeries(true);
						Courses cs=CoursesService.queryUnique(coursesQo);
						TeachersQo teachersQo=new TeachersQo();
						teachersQo.setSeachOrganization(true);
						teachersQo.setSeachUser(true);
						teachersQo.setTeacherId(cs.getUploader().getId());
						Teacher teacher=teachersService.queryUnique(teachersQo);
						teacher.setCoursesNum(teacher.getCoursesNum()-1);
						teachersService.update(teacher);
						SysProperties sysProperties=SysProperties.getInstance();
						String imgPath=sysProperties.get("imagePath");
						File dest = new File(imgPath+cs.getCoursesSeries().getCover());
						// 路径为文件且不为空则进行删除  
						if (dest.isFile() && dest.exists()) {  
							dest.delete();  
						}
						String videoPath=sysProperties.get("fileUploadPath");
						File dest2 = new File(videoPath+cs.getVideo());
						//						Encoder encoder = new Encoder();
						//						MultimediaInfo m = encoder.getInfo(dest2);
						//						System.out.println("-------"+m.getDuration());
						//						long ls = m.getDuration()/1000;
						//						int hour = (int) (ls/3600);
						//						int minute = (int) (ls/60);
						//						int second = (int) (ls-minute*60);
						if(cs.getCoursesSeries()!=null) {
							String[] fen1= cs.getViewTime().split(":");
							String[] fen= cs.getCoursesSeries().getTotalLength().split(":");
							String lengths="";
							Integer i=Integer.parseInt(fen[0]); 
							Integer j=Integer.parseInt(fen[1]); 
							Integer k=Integer.parseInt(fen1[0]); 
							Integer l=Integer.parseInt(fen1[1]); 
							int fens= i-k;
							int miaos= j-l;
							int s=0;
							if(miaos<0) {
								fens--;
								s=miaos+60;
							}
							lengths=fens+":"+s+"";
							cs.getCoursesSeries().setTotalLength(lengths);
							coursesSeriesService.update(cs.getCoursesSeries());
						}
						if(dest2.isFile() && dest2.exists()) {
							dest2.delete();
						}
						CoursesService.deleteById(Long.parseLong(id));
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(1);
						operationLog.setOperationDescription("课程删除!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						resMap.put("code", "200");
						resMap.put("message", "课程删除成功!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常!");
		return net.sf.json.JSONObject.fromObject(resMap).toString();
	}
	//审核
	@RequestMapping("/course_review")
	@ResponseBody
	public String course_Review(HttpServletRequest request,HttpSession session,HttpServletResponse response,String price,String id,Model model,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
					if(id==null && id=="") {
						resMap.put("code", "500");
						resMap.put("message", "没有找到此课程!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}else{
						CoursesQo coursesQo=new CoursesQo();
						coursesQo.setSeachUploader(true);
						coursesQo.setSeachCoursesSeries(true);
						coursesQo.setCoursesId(Long.parseLong(id));
						Courses cs=CoursesService.queryUnique(coursesQo);
						if(cs.getIsReview()==0 && cs.getIsPay()==2) {
							CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
							coursesSeriesQo.setSeachTeacher(true);
							coursesSeriesQo.setCoursesSeriesId(cs.getCoursesSeries().getId());
							CoursesSeries coursesSeries=coursesSeriesService.queryUnique(coursesSeriesQo);
							coursesSeries.setPrice(Integer.parseInt(price));
							cs.setIsReview(1);
							CoursesService.update(cs);
							coursesSeriesService.update(coursesSeries);
							resMap.put("code", "200");
							resMap.put("message", "审核通过!");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}else {
							cs.setIsReview(1);
							CoursesService.update(cs);
							resMap.put("code", "200");
							resMap.put("message", "审核通过!");
							return net.sf.json.JSONObject.fromObject(resMap).toString();
						}

					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}
			resMap.put("code", "500");
			resMap.put("message", "操作异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常!");
			return net.sf.json.JSONObject.fromObject(resMap).toString();
		} 

	}


	//课程添加
	@ResponseBody
	@RequestMapping(value= "/course_newAdds")
	public String saves(@RequestParam("pic")MultipartFile pic,@RequestParam("files")MultipartFile[] files,String fileName,HttpServletRequest request,HttpServletResponse response,CoursesSeriesCommand command ,@RequestParam(value="token", required=true) String token) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					} else if(user.getIsRole()==1 || user.getIsRole()==3) {
						if (pic.isEmpty()) {
							resMap.put("code", "500");
							resMap.put("message", "上传图片不可为空");
							return JSONObject.fromObject(resMap).toString();
						}
						int returnTag = -1;
						SysProperties sysProperties=SysProperties.getInstance();
						String fileTemPath=sysProperties.get("temporaryFileUploadPath");
						String filePath=sysProperties.get("fileUploadPath");
						String imgPath=sysProperties.get("imagePathAdmin");
						//获取图片原始文件名
						String originalFilename = pic.getOriginalFilename();
						System.out.println(originalFilename);
						//文件名使用当前时间
						String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
						// 获取上传图片的扩展名(jpg/png/...)
						String extension = FilenameUtils.getExtension(originalFilename);
						String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
						int firstIndex = fileName.indexOf('.'); //找到第一个空格所在位置
						//利用substring()方法根据第一个和最后一个单词的索引范围截取出第一个和最后一个单词
						String firstWord = fileName.substring(0,firstIndex); //截取出第一个单词
						boolean flag = false;
						// 判断文件格式是否合法
						for (String str : regular) {
							if (extension.equalsIgnoreCase(str)) {
								flag = true;
							}
						}
						if (!flag) {
							returnTag = 0;
							resMap.put("code", "500");
							resMap.put("message", "上传图片格式不正确！");
							return JSONObject.fromObject(resMap).toString();
						}
						// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
						String path =imgPath + firstWord + "." + extension;
						//图片上传的绝对路径

						File dir = new File(path);
						if (!dir.exists()) {
							dir.mkdirs();
						}
						// 上传图片
						pic.transferTo(new File(path));
						//保存课程信息
						TeachersQo teachersQo=new TeachersQo();
						teachersQo.setUserId(user.getId());
						teachersQo.setSeachOrganization(true);
						Teacher teacher=teachersService.queryUnique(teachersQo);
						if(teacher==null) {
							resMap.put("code", "500");
							resMap.put("message", "不是老师不能操作！");
							return JSONObject.fromObject(resMap).toString();
						}
						PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+"organization"+teacher.getTraininginstitution().getId()+"/"+fileName);
						File source = new File(filePath+"organization"+teacher.getTraininginstitution().getId()+"/"+fileName);
						if(command.getCourseShare()==1) {
							OrganizationQo organizationQo=new OrganizationQo();
							organizationQo.setOrganizationid(teacher.getTraininginstitution().getId());
							Organization organization= organizationService.queryUnique(organizationQo);
							if(organization.getStorageSize()==null) {
								organization.setStorageSize(source.length()/(1024*1024));
							}
							organization.setStorageSize(organization.getStorageSize()+source.length()/(1024*1024));
							organizationService.update(organization);
						}
						Encoder encoder = new Encoder();
						String length = "";
						MultimediaInfo m = encoder.getInfo(source);
						System.out.println("-------"+m.getDuration());
						long ls = m.getDuration()/1000;
						int hour = (int) (ls/3600);
						int minute = (int) (ls/60);
						int second = (int) (ls-minute*60);
						length = minute+":"+second;
						System.out.println(length);
						command.setTeacherId(teacher.getId());
						command.setVideo("organization"+teacher.getTraininginstitution().getId()+"/"+fileName);
						command.setCover(firstWord + "." + extension);
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
						java.util.Date  date=new java.util.Date();
						List<String> strlist=new ArrayList<String>();
						String dateString= new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
						for (int i=1 ;i<=files.length;i++ ) {
							int returnTags = -1;
							SysProperties sysPropertiess=SysProperties.getInstance();

							String courseMap=sysPropertiess.get("courseMap");
							//获取图片原始文件名
							String finetTalk = files[i-1].getOriginalFilename();
							System.out.println(finetTalk);
							//文件名使用当前时间
							String names = dateString+"-"+i;
							// 获取上传图片的扩展名(jpg/png/...)
							String extensions = FilenameUtils.getExtension(finetTalk);
							String[] regulars = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
							boolean flags = false;
							// 判断文件格式是否合法
							for (String str : regulars) {
								if (extensions.equalsIgnoreCase(str)) {
									flags = true;
								}
							}
							if (!flag) {
								returnTags = 0;
								resMap.put("code", "500");
								resMap.put("message", "上传图片格式不正确！");
								return JSONObject.fromObject(resMap).toString();
							}
							// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
							String paths =courseMap+"/"+user.getId() +"/" +names + "." + extension;
							strlist.add(user.getId() +"/" +names + "." + extension);
							//图片上传的绝对路径

							File dirs = new File(paths);
							if (!dirs.exists()) {
								dirs.mkdirs();
							}
							// 上传图片
							files[i-1].transferTo(new File(paths));
						}
						command.setImgList(strlist);
						command.setViewTime(length);
						command.setIsReview(0);
						command.setIsTopping(2);
						command.setIsSeriesLesson(2);
						ServiceResultDto serviceResultDto=CoursesService.findaCommand(command);
						if(serviceResultDto.getSuccess()) {
							OperationLog operationLog=new OperationLog();
							operationLog.setOperationType(2);
							operationLog.setOperationDescription("课程添加!");
							operationLog.setUserId(user);
							operationLog.setOperationTime(new Date());
							operationLog.setOperationUserName(user.getUserName());
							operationLogService.save(operationLog);
							resMap.put("code", "200");
							resMap.put("message", "课程添加成功！");
							return JSONObject.fromObject(resMap).toString();
						}
					}
				}else {
					resMap.put("code", "406");
					resMap.put("message", "请先登录!");
					return net.sf.json.JSONObject.fromObject(resMap).toString();
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "系统异常！");
			return JSONObject.fromObject(resMap).toString();
		}
		resMap.put("code", "500");
		resMap.put("message", "操作异常！");
		return JSONObject.fromObject(resMap).toString();
	}
	/**
	 * 删除子系列课程
	 * @param token
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete_subSeries")
	@ResponseBody
	public String delete_subSeries(@RequestParam(value="token", required=true) String token,String id) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			AdminSessionQo adminSessionQo=new AdminSessionQo();
			adminSessionQo.setToken(token);
			AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
			if(adminSession!=null) {
				UserQo userQo=new UserQo();
				userQo.setUserName(adminSession.getLoginName());
				User user= userService.queryUnique(userQo);
				if(user!=null) {
					user.setUserPassword("");
					if(user.getIsRole()==4) {
						resMap.put("code", "500");
						resMap.put("message", "最高管理员无法操作!");
						return net.sf.json.JSONObject.fromObject(resMap).toString();
					}
					CoursesQo coursesQo=new CoursesQo();
					coursesQo.setSeachCoursesSeries(true);
					coursesQo.setSeachUploader(true);
					coursesQo.setCoursesId(Long.parseLong(id));
					Courses courses= CoursesService.queryUnique(coursesQo);
					SysProperties sysProperties=SysProperties.getInstance();
					String videoPath=sysProperties.get("fileUploadPath");
					File dest2 = new File(videoPath+courses.getVideo());
					//					Encoder encoder = new Encoder();
					//					MultimediaInfo m = encoder.getInfo(dest2);
					//					System.out.println("-------"+m.getDuration());
					//					long ls = m.getDuration()/1000;
					//					int hour = (int) (ls/3600);
					//					int minute = (int) (ls/60);
					//					int second = (int) (ls-minute*60);
					if(courses.getCoursesSeries()!=null) {
						String[] fen1= courses.getViewTime().split(":");
						String[] fen= courses.getCoursesSeries().getTotalLength().split(":");
						String lengths="";
						Integer i=Integer.parseInt(fen[0]); 
						Integer j=Integer.parseInt(fen[1]); 
						Integer k=Integer.parseInt(fen1[0]); 
						Integer l=Integer.parseInt(fen1[1]);
						int fens= i-k;
						int miaos= j-l;
						int s=0;
						if(miaos<0) {
							fens--;
							s=miaos+60;
						}
						lengths=fens+":"+s+"";
						courses.getCoursesSeries().setTotalLength(lengths);
						CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
						coursesSeriesQo.setSeachTeacher(true);
						coursesSeriesQo.setCoursesSeriesId(courses.getCoursesSeries().getId());
						CoursesSeries coursesSeries=coursesSeriesService.queryUnique(coursesSeriesQo);
						coursesSeriesService.update(coursesSeries);
					}
					if(dest2.isFile() && dest2.exists()) {
						dest2.delete();
					}
					CoursesService.deleteById(Long.parseLong(id));
					OperationLog operationLog=new OperationLog();
					operationLog.setOperationType(1);
					operationLog.setOperationDescription("系列课删除!");
					operationLog.setUserId(user);
					operationLog.setOperationTime(new Date());
					operationLog.setOperationUserName(user.getUserName());
					operationLogService.save(operationLog);
					resMap.put("code", "200");
					resMap.put("message", "成功!");
					return JSONObject.fromObject(resMap).toString();
				}
			}
			resMap.put("code", "500");
			resMap.put("message", "请先登录！");
			return JSONObject.fromObject(resMap).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resMap.put("code", "500");
			resMap.put("message", "异常抛出！");
			return JSONObject.fromObject(resMap).toString();
		}

	}


}


